<template>
  <body id="poster">
    <div class="login-container">
      <h3 class="login-title">系统登录</h3>
      <el-form
          ref="formRef"
          :model="loginData"
          :rules="rules"
          status-icon
      >
        <el-form-item prop="username">
              <el-input
                  v-model="loginData.account"
                  clearable
                  placeholder="请输入账号"
                  :prefix-icon="User"
              ></el-input>
            </el-form-item>
        <el-form-item prop="password">
          <el-input
                  v-model="loginData.password"
                  clearable
                  placeholder="请输入密码"
                  show-password
                  :prefix-icon="Lock"
              >
          </el-input>
        </el-form-item>
        <el-form-item prop="identity">
<!--          <el-select v-model="value" class="m-2" placeholder="选择你的身份">-->
<!--            <el-option-->
<!--                v-for="item in IDOptions"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
          <el-form-item >
            <el-select v-model="loginData.userType" placeholder="选择你的身份">
              <el-option label="学生" value="student"></el-option>
              <el-option label="教师" value="teacher"></el-option>
              <el-option label="管理员" value="manage"></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item prop="code">
          <div style="display: flex" >
            <el-input v-model="loginData.code"
                      placeholder="验证码"
                      style="height: 38px"
            >
            </el-input>
            <Identify :identifyCode="identifyCode" @click="refreshCode" style="margin-left: 20px"/>
          </div>
        </el-form-item>
      </el-form>
      <div style="display: flex;justify-content: space-between;">
        <div>
          <el-checkbox v-model="loginData.checked" class="rememberPwd">
            记住密码
          </el-checkbox>
        </div>

      </div>
      <div class="login-button">
        <el-button type="primary" @click="submitForm('formRef')"
        >登录</el-button
        >
        <!--        <el-button class="shou" @click="register">注册</el-button>-->
      </div>
    </div>
  </body>
</template>

<script>
import {User,Lock} from '@element-plus/icons'
import Identify from "../../components/Identify.vue";
import {ElMessage} from "element-plus";
import {Base64} from "js-base64";
import service from "../../utils/axios";


export default {
  name:"login",
  components:{
    Identify,
  },
  setup(){
    return{
      User,
      Lock,
    }
  },
  data(){
    return{
      formRef:'',
      identifyCode:'',
      identifyCodes:"1234567890abcdefghijklmnopqrstuvwxyz",
      value:'',

      loginData: {
        account: "",
        password: "",
        code: "",
        checked: [],
        userType:'',
      },
      rules:{
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { max: 15, message: "不能大于10个字符", trigger: "blur" },
         ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min:3,max: 15, message: "密码长度在3-15位之间", trigger: "blur" },
         ],
        code:[
          { required: true,message: "请输入验证码", trigger: "blur"},
          { min:4,max: 4, message: "验证码长度为4位", trigger: "blur" },
        ]
      },

    }
  },
  created() {
    this.hasUserCodeOrPassword();	//调用函数
    this.makeCode(this.identifyCode,4);
  },
  methods:{
    submitForm() {
      if (this.loginData.code !== this.identifyCode) {
        ElMessage.error('验证码不正确!!');
        return false;
      } else {
        this.$refs.formRef.validate((valid) => {
          // 会输出true或者false
          if (valid) {
            console.log("123")
            //向后端请求登录页面
            console.log(this.loginData.userType)
            if (this.loginData.userType === "student" || this.loginData.userType === "manager") {
              console.log("123")
              service.post("/tb-student/login" , this.loginData).then(res => {
                alert(res.data);
                console.log(res.data)
                if (res.data.code === 200) {
                  ElMessage.success("登录成功")
                  this.$store.commit("SET_TOKEN", res.data.data.token);
                  this.$store.commit("SET_USERINFO", res.data.data.user);
                  this.$store.commit("SET_USERTYPE", this.loginData.userType);
                  router.push("/home");
                } else {
                  ElMessage.error('登录失败!!');
                  return false;
                }
              })
            }
              else if(this.loginData.userType === "teacher"){
              console.log("123")
              service.post("/tb-teacher/login" , this.loginData).then(res => {
                alert(res.data);
                console.log(res.data)
                if (res.data.code === 200) {
                  ElMessage.success("登录成功")
                  this.$store.commit("SET_TOKEN", res.data.data.token);
                  this.$store.commit("SET_USERINFO", res.data.data.user);
                  this.$store.commit("SET_USERTYPE", this.loginData.userType);
                  this.router.replace("/home-s");
                } else {
                  ElMessage.error('登录失败!!');
                  return false;
                }
              })
              }
            } else {
            console.log("123")
              ElMessage.error('登录失败!!');
              return false;
            }

        })
      }
      let isChecked = this.loginData.checked?.length === 1
      //判断是否点击记住密码
      if (isChecked) {
        localStorage.setItem('account', this.loginData.account)
        localStorage.setItem(
            'password',
            Base64.encode(this.loginData.password),		//base加密
        )
      } else {
        localStorage.removeItem('account')
        localStorage.removeItem('password')
      }
    },
    makeCode(o,l){
      for(let i=0;i<l;i++){
        this.identifyCode +=this.identifyCodes[this.randomNum(0,this.identifyCodes.length)];
      }
    },
    refreshCode(){
      this.identifyCode="";
      this.makeCode(this.identifyCode,4);
    },
    randomNum(min,max){
      return Math.floor(Math.random()*(max-min)+min);
    },
    //在setup中，用来加载页面时，查看账户密码是否存在
    hasUserCodeOrPassword(){
      if (localStorage.getItem('account') && localStorage.getItem('password')) {
        this.loginData.account = localStorage.getItem('account')
        this.loginData.password = Base64.decode(localStorage.getItem('password'))//解密
        //loginData.checked.push(true)
      }
    }
  }
}
</script>

<style>
  #poster {
    background: url("src/assets/images/body.jpg") no-repeat;
    background-size: cover;
    height: 100%;
    width: 100%;
    position: fixed;
}
  .login-container {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 150px auto;
    width: 400px;
    padding: 35px 35px 35px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }
  .login-title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #505458;
  }
  .login-button{
    margin: 20px auto 0px auto;
    text-align: center;
  }
</style>

